package de.unistuttgart.iaaskpimonitoring.esper.eventmanagement;

import java.util.List;

import javax.jms.Connection;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;

import de.unistuttgart.iaaskpimonitoring.esper.configurationmanagement.Configuration;

public class Filter {
	private FilterElement firstFilterElement;
	private boolean filterActivated = false;
	private String targetEngineURI;
	private Connection conn;

	// The cfg object contains the treatment chain that is WFMS specific
	public Filter(Configuration cfg, String targetEngineURI) {
		Context ctx = new InitialContext();
		TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
				.lookup(cfg.getTopicConnectionFactoryName());
		Topic messageSource = (Topic) ctx.lookup(cfg.getTopicName());

		conn = topicConnectionFactory.createTopicConnection();
		FilterElement prevfe = null;
		FilterElement currfe = null;

		for (String fEName : cfg.getFilterElementList()) {
			currfe = (FilterElement) Class.forName(fEName).newInstance();
			if (prevfe != null) {
				prevfe.setSuccessor(currfe);
			} else {
				setFirstFilterElement(currfe);
			}
			prevfe = currfe;
		}
		
		getFirstFilterElement().setTargetEngineURI(targetEngineURI);

	}

	public FilterElement getFirstFilterElement() {
		return firstFilterElement;
	}

	public void setFirstFilterElement(FilterElement firstFilterElement) {
		this.firstFilterElement = firstFilterElement;
	}

	public boolean isFilterActivated() {
		return filterActivated;
	}

	public void setFilterActivated(boolean filterActivated) {
		this.filterActivated = filterActivated;
	}

	public String getTargetEngineURI() {
		return targetEngineURI;
	}

	public void stopFilter() {
		conn.stop();
		setFilterActivated(false);
	}

	public void startFilter() {
		conn.start();
		setFilterActivated(true);
	}

	public void closeFilter() {
		conn.close();
		setFilterActivated(false);
	}

	// We can change the target ESPER engine. By the way, for another PPM list
	// to process, coming from another PPMXMLFile, we prefer having another
	// dedicated
	// ESPER engine to process the metrics.
	public void setTargetEngineURI(String targetEngineURI) {
		stopFilter();
		this.targetEngineURI = targetEngineURI;
		firstFilterElement.setTargetEngineURI(targetEngineURI);
		startFilter();
	}

	// We can change the topic the Adapter is consuming from (makes sense as
	// long as the new source WFMS produces the same type of messages in the
	// middleware)
	public void changeMessageSource(String topicName,
			String topicConnectionFactoryName) {
		stopFilter();
		Context ctx = new InitialContext();
		TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
				.lookup(topicConnectionFactoryName);
		Topic messageSource = (Topic) ctx.lookup(topicName);
		startFilter();
	}

}
